package com.net.common.encryption;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

import com.google.common.base.Strings;

/**
 * @author  on 2017/6/21.
 * Blowfish加解密
 */
public class BlowfishUtil {

    public static String encrypt(String key, String data) throws Exception {
        if (Strings.isNullOrEmpty(data) || Strings.isNullOrEmpty(key)) {
            return null;
        }

        byte[] keyData = key.getBytes();
        SecretKeySpec ks = new SecretKeySpec(keyData, "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, ks);

        // encrypt message
        byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
        return Hex.encodeHexString(encrypted);
    }

    public static String decrypt(String key, String data) throws Exception {
        if (Strings.isNullOrEmpty(data) || Strings.isNullOrEmpty(key)) {
            return null;
        }

        byte[] keyData = key.getBytes();
        SecretKeySpec ks = new SecretKeySpec(keyData, "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.DECRYPT_MODE, ks);

        byte[] decrypted = Hex.decodeHex(data.toCharArray());
        return new String(cipher.doFinal(decrypted), "UTF-8");
    }
}
